﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace TCP客户端连接发起测试
{
    public class TcpClient
    {
        string serverIP = "192.168.1.64";
        int serverPort = 6612;

        public TcpClient() {
            //定义一个套接字监听
            Socket socketclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //获取文本框中的IP地址
            IPAddress address = IPAddress.Parse(serverIP);
            //将获取的IP地址和端口号绑定在网络节点上
            IPEndPoint point = new IPEndPoint(address, serverPort);
            //连接
            socketclient.Connect(point);

            byte[] bytes = System.Text.Encoding.UTF8.GetBytes("AT+NodeName=?\r\n");

            socketclient.Send(bytes);

            byte[] recvBuf = new byte[1024];
            int n = socketclient.Receive(recvBuf);
            if (n <= 0) {
                socketclient.Close();
                return;
            }
            byte[] buf = new byte[n];
            Array.Copy(recvBuf, buf, n);
            string msg = Encoding.UTF8.GetString(buf);
            Console.WriteLine("接收到的数据为：" + msg);

            socketclient.Close();

        }
    }
}
